import logging
import os
import shutil

import constants
from dao.video_resource_dao import VideoResourceDao
from models import VideoSource
from service.task_video_service import TaskVideoService


class VideoService:
    def __init__(self):
        self.video_resouce_dao = VideoResourceDao()
        self.task_video_service = TaskVideoService()

    def save_video_source(self, video):
        video_url = constants.SITE_NAME + "/" + video.get("id") + "/index.m3u8"
        image_url = constants.SITE_NAME + "/" + video.get("id") + "/" + video.get("v_id") + ".js"
        model = VideoSource(
            id=video.get("id"),
            title=video.get("title"),
            cover=image_url,
            play_path=video_url,
            type=1,
            tags=video.get("type_name"),
            category=video.get("type_id"),
            remark=video.get("title_en"),
            duration=video.get("duration_str"),
            play_time=video.get("duration"),
            price=self.get_price(video.get("duration")),
            create_time=video.get("create_time"),
            offline_time=video.get("release_time"),
            online_time=video.get("release_time"),
            user_id="admin",
            langs=2,
            actors=video.get("author"),
            likenum=0,
            favnum=0,
            sharenum=0,
            diskenum=0,
            downnum=0,
            planum=video.get("play_num"),
            preview="",
            recom_start=1,
            sort=1,
            show_type=1,
            state=1,
        )
        # 更新任务状态
        self.task_video_service.update_task_video_is_down_by_id(video.get("id"), 1)
        # 先检查视频是否已存在
        if self.video_resouce_dao.get_video_by_id(video.get("id")) is None:
            # 如果视频不存在，则创建新视频
            self.video_resouce_dao.create_video(model)
            return True
        return False

    def get_video_info(self, video_id):
        video_info = self.video_resouce_dao.get_video_by_id(video_id)
        return video_info

    def get_price(self, duration):
        if duration <= 180:
            return 50
        elif 180 < duration <= 600:
            return 60
        elif 600 < duration <= 1200:
            return 80
        elif 1200 < duration <= 2100:
            return 99
        elif 2100 < duration <= 3000:
            return 128
        else:
            return 168

    def delete_video(self, video_id: str):
        # 还要删除物理文件
        directory = os.path.dirname(constants.DOWNLOAD_PATH)
        folder_path = os.path.join(directory, video_id)
        # 验证 video_id 的合法性
        if not video_id.isalnum():
            logging.error(f"无效的 video_id: {video_id}")
            return 0

        if os.path.exists(folder_path):
            # 尝试删除目录及其所有内容
            try:
                self.video_resouce_dao.delete_task_video_by_id(video_id)
                shutil.rmtree(folder_path)
                logging.info(f"文件夹 {folder_path} 及其内容已成功删除。")
                return 1
            except OSError as e:
                logging.error(f"删除文件夹 {folder_path} 时发生错误：{e}")
            except Exception as e:
                logging.error(f"删除视频资源时发生未知错误：{e}")
                print(f"删除视频资源时发生未知错误：{e}")
            return 0
